package com.lsh.oms.provider.service.rpc;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.status.UpdateSoInfoDto;
import com.lsh.oms.api.model.status.UpdateStatusDto;
import com.lsh.oms.api.service.status.IUpdateStatusRpcService;
import com.lsh.oms.core.constant.Constants;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderOperateType;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.OrderUpdateService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 19/2/23
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "dubbo")
public class ModifyStatusRpcServiceImpl implements IUpdateStatusRpcService {

    private static Logger logger = LoggerFactory.getLogger(ModifyStatusRpcServiceImpl.class);

    @Autowired
    private EsProxy esProxy;

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderUpdateService orderUpdateService;

    @Override
    public CommonResult<Object> updateStatusOFC(UpdateStatusDto dto) {
        boolean checkReslut = checkCommonParams(dto);
        CommonResult<Object> result = new CommonResult<Object>();
        if (!checkReslut) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("请求参数不合法，请检验。");
            return result;
        }
        String logSign = dto.getErp() + "-" + dto.getOrderNo();
        logger.info(logSign + ":OFC更新订单状态入参 －－ " + JsonUtils.obj2Json(dto));
        OrderHead headDto = orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (headDto == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            return result;
        }
        if (!headDto.getOrderStatus().equals(OrderStatus.ORDER_COMMITED_OFC.getIndex())) {
            if (headDto.getOrderStatus().equals(OrderStatus.ORDER_WM_NEW.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是物美以创建，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }

            return result;
        }

        JSONObject extObject;
        if (StringUtils.isBlank(headDto.getExt())) {
            extObject = new JSONObject();
        } else {
            extObject = JSONObject.parseObject(headDto.getExt());
        }
        extObject.put(Constants.WAREHOUSE_CODE, dto.getWarehouseCode());
        extObject.put("mpCustCode", dto.getMisExt());
        extObject.put("saleModel", dto.getSaleModel());
        extObject.put("deliveryType", dto.getDeliveryType());
        String ext = extObject.toJSONString();

        OrderHead entity = new OrderHead();
        entity.setOrderCode(dto.getOrderNo());
        entity.setOrderStatus(OrderStatus.ORDER_WM_NEW.getIndex());
        entity.setUpdateTime((int) (System.currentTimeMillis() / 1000));
        entity.setLackDeliveryType(dto.getLackDeliveryType());
        entity.setSoCodes(dto.getSoCode());
        entity.setExt(ext);
        boolean updateFlag = orderUpdateService.updateOrderStatus(dto.getOrderNo(), entity, OrderOperateType.ORDER_COMMITTED_TO_WMS, headDto.getVenderId()) > 0;
        logger.info(logSign + ": 更新DB订单状态－－ " + updateFlag + "," + dto.getOrderNo());
        OrderHead esOrderHead = new OrderHead();
        esOrderHead.setOrderStatus(OrderStatus.ORDER_WM_NEW.getIndex());
        esOrderHead.setOrderCode(dto.getOrderNo());
        esOrderHead.setSoCodes(dto.getSoCode());
        esOrderHead.setExt(ext);
        if (dto.getLackDeliveryType() != null) {
            esOrderHead.setLackDeliveryType(dto.getLackDeliveryType());
        }

        esProxy.editIndex(EsProxy.transformToOrderHeadForEs(esOrderHead), logSign);

        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(updateFlag);
        result.setMessage("");
        return result;
    }

    @Override
    public CommonResult<Boolean> updateOrderInfoOFC(UpdateSoInfoDto dto) {
        CommonResult<Boolean> result;
        try {
            if (dto.getOrderNo() == null || dto.getOrderNo() == 0L || MapUtils.isEmpty(dto.getSoBillCodeMap())) {
                throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
            }
            OrderHead orderHead = orderQueryService.findByCode(dto.getOrderNo(), false, false);
            if (orderHead == null) {
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "查询不到订单信息，订单号：" + dto.getOrderNo());
            }

            String logSign = "【" + dto.getOrderNo() + " - 更新订单soCode】";
            String soCodes = orderHead.getSoCodes();
            if (StringUtils.isNotEmpty(soCodes)) {
                List<String> psiSoBillCodes = Arrays.asList(soCodes.split(","));

                List<String> codesList = new ArrayList<>(psiSoBillCodes.size());
                for (String psiSoBillCode : psiSoBillCodes) {
                    String codes = psiSoBillCode;
                    Set<String> wmSoBillCodes = dto.getSoBillCodeMap().get(psiSoBillCode);
                    if (CollectionUtils.isNotEmpty(wmSoBillCodes)) {
//                        throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "该psi SoBillCode查询不到wm SoBillCode，SoBillCode：" + psiSoBillCode);
                        codes = psiSoBillCode + "|" + org.springframework.util.StringUtils.collectionToDelimitedString(wmSoBillCodes, "|");
                    }
                    codesList.add(codes);
                }

                OrderHead entity = new OrderHead();
                entity.setSoCodes(org.springframework.util.StringUtils.collectionToDelimitedString(codesList, ","));
                int update = orderUpdateService.updateOrderHead(dto.getOrderNo(), entity);
                if (update > 0) {
                    OrderHead esOrderHead = new OrderHead();
                    esOrderHead.setOrderCode(dto.getOrderNo());
                    esOrderHead.setSoCodes(entity.getSoCodes());
                    esProxy.editIndex(EsProxy.transformToOrderHeadForEs(esOrderHead), logSign);
                }
            }

            result = new CommonResult<>(ReturnCode.REQUEST_SUCCESS, "success", Boolean.TRUE);
        } catch (BusinessException e) {
            logger.error("更新订单信息，业务异常，参数：" + JSON.toJSONString(dto), e);
            result = new CommonResult<>(e.getCode(), e.getMessage(), Boolean.FALSE);
        } catch (Exception e) {
            logger.error("更新订单信息，系统异常，参数：" + JSON.toJSONString(dto), e);
            result = new CommonResult<>(ReturnCode.REQUEST_FAIL, "系统异常", Boolean.FALSE);
        }

        return result;
    }

    private boolean checkCommonParams(UpdateStatusDto dto) {
        if (dto == null || StringUtils.isEmpty(dto.getErp())) {
            return false;
        }
        if (dto.getOrderNo() == null) {
            return false;
        }
        if (dto.getSoCode() == null) {
            return false;
        }
        return true;
    }

}
